<template>
  <div class="deploy-bp-detail ">
      
      
      <el-card shadow="never">
      	<i class="iconfont icon-bianpaixin"></i>
      	
	      <el-table
	      	ref="bpTable"
			    :data="bpeditDatas"
			    style="width: 100%"
			    @row-click="toggleRow"
			    default-expand-all
			    >
			    <el-table-column  type="expand">
			      <template slot-scope="props">
			        <el-form 
			        	v-if="props&&props.row&&props.row.insts&&props.row.insts.length" 
			        	v-for="inst in props.row.insts" label-position="left" inline class="demo-table-expand">
			          <el-form-item label="IP:">
			            <span >{{ inst.ip || '-' }}</span>
			          </el-form-item>
			          <el-form-item label="状态:">
			            <span class="inst-status" v-html="appStatusFilter(inst.status)"></span>
			          </el-form-item>
			          <el-form-item label=" ">
			            <el-button 
			            	v-if="inst.status!=10"
			            	type="text" size="mini" @click="goDetail(inst,props.row.index)">
				      	 		<i class="iconfont icon-detail" title="详情" ></i>
				      	  </el-button>
				      	  <el-button
				      	  	v-if="(inst.status==3||inst.status==4)&&inst.instId"
				      	  	 type="text" size="mini" @click="deleteIp(inst,props.row ,props.row.index)">
				      	 		<i class="iconfont icon-shanchu" title="删除" ></i>
				      	  </el-button>
				      	  <el-button 
			            	type="text" size="mini" @click="goShiliList(inst,props.row,props.row.index)">
				      	 		<i class="iconfont icon-pointer" title="更多操作" ></i>
				      	  </el-button>
			          </el-form-item>
			        </el-form>
			        <div v-if="!props.row||!props.row.insts||!props.row.insts.length" class="grey" style="padding: 10px 50px;font-size: 12px;">
			        	没有可以展示的数据
			        </div>
			      </template>
			    </el-table-column>
			    <el-table-column
			      prop="templateName"
			      label="应用名称"
			      width="">
			    </el-table-column>
			    <el-table-column
			      prop="name"
			      label="部署类型"
			      align="center"
			      width="120">
			        <template slot-scope="scope" >
			        	<span v-if="scope.row" v-html="deployTypeFilter(scope.row.deployType,scope.row.templateType)">
			        	</span>
				      </template>
			    </el-table-column>
			    <el-table-column
			      prop="address"
			      width="120"
			      label="应用状态">
			       <template slot-scope="scope">
			      	 <span v-if="scope.row" 
			      	 	v-html="bianpaiGroupStatusFilter(scope.row.status)"></span>
				     </template>
			    </el-table-column>
			    <el-table-column
			    	align="right"
			    	width="300"
			      label="操作">
			        <template v-if="scope.row" slot-scope="scope">
			      	  	<el-button type="text" v-if="[0,1,5].indexOf(scope.row.status)==-1" 
			      	  		 @click="eidtDeploy(scope.row)" >
			      	  		<i class="iconfont icon-write" title="编辑" ></i>
				      	  </el-button>
				      	  <!--<el-button v-if="[0,1,5].indexOf(scope.row.status)==-1" 
				      	  	@click="deployAggin(scope.row)">
			      	  		重新部署
				      	  </el-button>-->
				      </template>
			    </el-table-column>
			  </el-table>
			  
			  
	      
      	
      </el-card>
      
      <!--<template slot-scope="scope">
			      	<div class="inst-box" v-if="scope.row.insts&&scope.row.insts.length">
			      		<div v-for="inst in scope.row.insts">
			      			{{inst.ip}}
			      			<span v-html="appStatusFilter(inst.status)"></span>
			      		</div>
		      		</div>
		      		<div v-else>&nbsp;</div>
				    </template>-->
      
      <!--<el-row v-for="item in bpeditDatas" v-if="item">
      	<el-col :span="6">
      		{{item.appType}}
      	</el-col>
      	<el-col :span="6">
      			<span v-html="deployTypeFilter(item.deployType,item.templateType)"></span>
      	</el-col>
      	<el-col :span="6">
      		<div class="inst-box" v-if="item.insts&&item.insts.length">
	      		<div v-for="inst in item.insts">
	      			{{inst.ip}}
	      			<span v-html="appStatusFilter(inst.status)"></span>
	      		</div>
      		</div>
      		<div v-else>&nbsp;</div>
      	</el-col>
      	<el-col :span="6">
      		<span v-html="bianpaiGroupStatusFilter(item.status)"></span>
      	</el-col>
      </el-row>-->
      
      <deployConfigDialog
				ref="deployConfigDialog"
				@close="saveDeployConfig"
				></deployConfigDialog>
      
  </div>
</template>


<script>
	import { getInstStatus } from '@/service/swagger/AcAppInstController';
	import {bianpaiGroupStatusFilter,deployTypeFilter,appStatusFilter} from "@/filters/status/index";
	import {listenner} from "@/utils/statuslistener" ;
	import deployConfigDialog from "./deployConfigDialog";
	import {getInstHistory,getInstHistoryTemplate,updateOrchestrateInstItem,againOrchestrate,deleteOrchestrateItemInst} from "@/service/swagger/OrchestrateController";
	import {getTemplateById} from'@/service/swagger/AcTemplateController';
	import {deleteSL} from "@/service/swagger/InstanceController";
	
  export default {
    components:{
    	deployConfigDialog,
    },
    data(){
      return{
      		editeditDatas : null,
      		data : null , // 父级传的基础data
					bpeditDatas : [], // 显示用data
					bianpaiGroupStatusFilter : bianpaiGroupStatusFilter ,
					deployTypeFilter : deployTypeFilter ,
					appStatusFilter : appStatusFilter,
      }
    },
    mounted() {
      
    },
    methods:{
    	refresh(){
    		this.initData();
    	},

      initData(data,allData){
      	console.log("接收到data：",data)
      	if(data){
      		this.data = data ;
      	}
      	this.renderDatas(allData);
      },
      getItemData(allData){
    		getInstHistory({
      		id: this.data.serviceInstId,
      	}).then(ret=>{
      		if(!ret.code&&ret.data){
						this.renderDatas(ret.data)
      		}
      	})
      },
      
      renderDatas(data){
      	let arr = data.templateInsts ;
  			this.bpeditDatas = arr;
				let hasNoInstId , isNotStaticStatus ;
				arr.forEach(item=>{
					if(bianpaiGroupStatusFilter(item.status).indexOf("...")>-1){
  					isNotStaticStatus = true ;
  				}
					item.insts.forEach(el=>{
						if(!el.instId){
  						hasNoInstId = true ;
  					}
					})
				})
				if(hasNoInstId||isNotStaticStatus){
					setTimeout(()=>{
						if(window.location.href.indexOf("isHistory")>-1){
							this.getItemData()
						}
					},3000)
				}else{
					this.addStatusListener();
				}
      },
      
      addStatusListener(){
      	const statusStatic = (status) => {
					// 是否是稳定状态
					const isStatic = !(appStatusFilter(status).indexOf("...") > -1);
					return isStatic;
				}
				let unStaticArr = [];
				// 添加  status 监听
				this.bpeditDatas.forEach(item=>{
					if(item&&item.insts&&item.insts.length){
						item.insts.forEach(el=>{
	      			if (!statusStatic(el.status)&&el.instId) {
								unStaticArr.push(el.instId)
							}
	      		})
					}
      	})
				if (unStaticArr && unStaticArr.length) {
					listenner({
						api: {
							serviceFN: getInstStatus,
							params: unStaticArr,
						},
						callBack: (ret) => {
	
							let hasAllStatusStaticed = true;
							let needSend = [] ;
							ret.data.forEach(data => {
								if (!statusStatic(data.status)) {
									hasAllStatusStaticed = false;
								}
								this.bpeditDatas.forEach((item,index)=>{
									
				      		item.insts.forEach(el=>{
				      			if (data.instId == el.instId) {
				      				if(el.status != data.status){
				      					needSend.push({
				      						data : item,
				      						index : index,
				      					}) ;
				      				}
										}
				      		})
				      		
				      	})
							});
							if(needSend&&needSend.length){
								needSend.forEach(el=>{
									this.getItemData();
								})
		      		}
							// this.$refs.listTpml.loadTableData(tableData)
							return hasAllStatusStaticed;
						},
					}, this)
				}
				
      },
      
      eidtDeploy(row){
      	this.$refs.bpTable.toggleRowExpansion(row)
      	
      	this.editDatas = row;
      	// console.log(666,{...this.editDatas},{...this.data})
      	if(!this.editDatas){
      		this.pleaseChoseTemp();
      		return;
      	}
      	let config = this.editDatas.deployService || {} ;
      	let disabledIps = [];
      	for(let i in this.editDatas.insts){
      		let s = this.editDatas.insts[i].status ;
      		if([0,1,6,7,8,9,10].indexOf(s)>-1){
      			disabledIps.push(this.editDatas.insts[i].ip)
      		}
      	}
      	
      	this.$refs.deployConfigDialog.open().initData({
      		...this.editDatas,
      		deployType : this.editDatas.deployType ,
      		templateType : this.editDatas.templateType ,
      		itemInstId : this.editDatas.itemInstId ,
      		templateId : config.templateId,
      		appName : config.appName || "" ,
      		clusterId : config.clusterId,
	      	clusterName : config.clusterName || "" ,
	      	// needips : config.clusterName ,
	      	ips : config.ips || [] ,
	      	disabledIps : disabledIps ,
	      	// ipsString : "", // 用于验证
	      	varsInfoShili : [{
	      		varsName : "",
	      		varsValue : config.spec || ""
	      	}],
	      	varsInfoPort : (config.portMappings ? config.portMappings.map(el=>{
	      		return {
	      			defaultValue : el.vmPort || "",
	      			varsName : el.dockerPort|| "",
	      			envType :2,
	      		}
	      	}) : null) ,
	      	varsInfoEnv : (config.envs ? config.envs.map(el=>{
	      		return {
	      			varsName : el.name|| "",
	      			defaultValue : el.value|| "",
	      			envType :1,
	      		}
	      	}) : null),
	      	varsInfoVolume : (config.volumes ? config.volumes.map(el=>{
	      		return {
	      			defaultValue : el.dockerPath|| "",
	      			envType :4,
	      		}
	      	}) : null),
	      	varsInfoLog : (config.logVolumes ? config.logVolumes.map(el=>{
	      		return {
	      			varsValue : el.logPath|| "",
	      			envType :5,
	      		}
	      	}):null),
	      	// varsInfo : [],
	      	templateConfigs : (config.instConfigs ? config.instConfigs.map(el=>{
	      		return {
	      			configName : el.configName|| "",
	      			configParentPath : el.configParentPath|| "",
	      			configSourceFile : el.configSourceFile|| "",
	      			varsValue : el.instId|| "",
	      			usedMethod : el.usedMethod|| "",
	      		}
	      	}) : null),
      	}, null , true , true )
      	
      	
      },
      
      
      saveDeployConfig(name,data,validated){
      	// console.log("表单验证",name,data,validated)
      	if(validated){
      		// 表单验证成功
      		
      		this.deployAggin(this.editDatas,()=>{
      			updateOrchestrateInstItem({
	      			itemInstId : this.editDatas.itemInstId,
	      			deployService : {
	      				appName : data.appName  ,
	      				clusterId : data.clusterId  ,
								clusterName : data.clusterName  ,
								deployInstCounts : data.deployInstCounts  ,
								deployModel : data.deployModel,
								spec : data.varsInfoShili[0].varsValue || ""  ,
								envs : data.varsInfoEnv.map(el=>{
									return {
										name : el.varsName ,
										value : el.varsValue ,
									}
								}),
								instConfigs : data.templateConfigs.map(el=>{
									return {
										configName : el.configName ,
										configParentPath : el.configParentPath,
										configSourceFile : el.configSourceFile,
										// instId : el.varsValue ,
										usedMethod : el.usedMethod ,
									}
								})  ,
								ips : data.ips  ,
								logVolumes :  data.varsInfoLog.map(el=>{
									return {
										logPath : el.varsValue ,
									}
								}) ,
								portMappings :  data.varsInfoPort.map(el=>{
									return {
										dockerPort : el.varsName ,
										vmPort : el.varsValue ,
									}
								})    ,
								templateId : data.templateId  ,
								volumes : data.varsInfoVolume.map(el=>{
									return {
										dockerPath : el.varsValue ,
									}
								}) ,
	      			}
	      		}).then(ret=>{
	      			if(!ret.code){
	      				// this.refresh();
	      				againOrchestrate({
				      		serviceInstId : this.editDatas.serviceInstId,
				      		serviceTemplateId : this.data.serviceTemplateId,
				      		templateId : this.editDatas.templateId,
				      	}).then(ret=>{
				      		if(!ret.code){
				      			this.getItemData()
				      		}
				      	})
	      				// this.$emit("refresh");
	      			}
	      		});
      		})
      		
      		
      	}
      },
      
      
      deployAggin(row,fn){
      	// console.log(row)
      	this.$confirm("编辑后需要重新部署成效,是否重新部署？", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					fn&&fn();
				})
      },
      
      
      pleaseChoseTemp(){
      	this.$message({message: '请选择可用的模板',type: 'error',duration : 2000,});
      },
      
      
      deleteIp(row,el,index){
				this.$confirm("确定删除该实例？", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					deleteSL(row.instId).then(ret => {
						if (ret && ret.code == 0) {
							this.getItemData();
							this.$message({ showClose: true, message: '删除成功！', type: 'success' })
						}
					})
				})
			},
			
			
			goDetail(row,index){
      	if(row.templateType==2){
      		this.$router.push({
	      		path :  "/sl/zjdetail", 
	      		query : {
	      			appType : "zujian",
	      			name : row.instName || "",
	      		}
	      	})
      	}else{
      		this.$router.push({
	      		path :  "/sl/yydetail", 
	      		query : {
	      			appType : "yingyong",
	      			id : row.instId,
	      			deploy : row.deployType,
	      		}
	      	})
      	}
      },
      
      goShiliList(inst,row,index){
      	if(row.templateType==2){
      		this.$router.push({
	      		path :  "/sl/zj", 
	      		query : {
	      			name : inst.instName || "",
	      		}
	      	})
      	}else{
      		this.$router.push({
	      		path :  "/sl/yy", 
	      		query : {
	      			name : inst.instName || "",
	      		}
	      	})
      	}
      },
      
      toggleRow(row, event, column){
      	this.$refs.bpTable.toggleRowExpansion(row)
      	//console.log(row, event, column)
      },
      

    }
  }
</script>


<style lang="scss" >
	@import "../../../../styles/variables.scss";
	
	.deploy-bp-detail {
		position: relative;
		margin:20px;
		box-sizing:border-box;
		
		
		.el-card {
	    border: 1px solid $borderGrey;
	    .el-card__body {
	    	
	      overflow: hidden;
	      padding:0 0 0 110px !important;
	    }
	  }
		
		
	  .el-card__body > i {
	    display: block;
	    width: 110px;
	    text-align: center;
	    height: 110px;
	    position: absolute;
	    left: 1px;
	    top: 1px;
	    font-size: 70px;
	    color: $mainBlue;
	    line-height: 110px;
	  }
	  
	  .el-table {
	  	min-height: 110px;
	  	border-left: 1px solid $borderGrey;
	  	margin-bottom: -1px;
	  	
	  	.el-table__row {
	  		cursor: pointer;
	  	}
	  	td {
	  		button {
	  			i {
	  				font-size: 14px;
	  			}
	  		}
	  	}
	  	
	  	
	  	.el-table__expanded-cell {
	  		padding: 0 !important;
	  		.el-form {
	  			width: 100%;
	  			padding: 10px 50px 0 !important;
	  			margin: 0 !important;
	  			min-height: auto !important;
	  			border-bottom: 1px solid $borderGrey;
	  			
	  			&:nth-last-child(1) {
	  				border: none;
	  			}
	  			
	  			.el-form-item {
	  				min-width: auto !important;
	  				margin-right: 50px !important;
	  				margin-bottom: 5px !important;
	  				.el-form-item__label {
	  					font-size: 12px;
	  					color: #999;
	  				}
	  				.el-form-item__content {
	  					font-size: 12px;
	  					
	  					.inst-status {
	  						display: inline-block;
	  						min-width: 65px;
	  					}
	  				}
	  				
	  			}
	  		}
	  		
	  		
	  	}
	  	
	  	button {
	  			padding: 0 !important;
	  		}
	  }
  
	}
	
</style>